﻿using System.ComponentModel;
using System.Runtime.CompilerServices;
using FixtureManageSystem.Commands;
using FixtureManageSystem.Models;
using System.Windows.Input;
using System.Collections.ObjectModel;
using System;
using System.Linq;
using CommunityToolkit.Mvvm.Input;
using System.Windows.Controls;
using CommunityToolkit.Mvvm.ComponentModel;



namespace FixtureManageSystem.ViewModels
{
    public class EmployeeViewMode : ObservableObject
    {

        public void SetDataGrid(DataGrid d)
        {
            datagrid = d;
        }
        private DataGrid datagrid;

        private ICommand addCommand;
        public ICommand AddCommand
        {
            get { return addCommand; }
            set { addCommand = value; }
        }

        private ICommand getEmployeeCommand;
        public ICommand SearchCommand
        {
            get { return getEmployeeCommand; }
            set { getEmployeeCommand = value; }
        }

        private Employee _selectedEmployee;
        public Employee SelectedEmployee
        {
            get => _selectedEmployee;
            set => SetProperty(ref _selectedEmployee, value);
        }

        private ICommand deleteCommand;
        public ICommand DeleteCommand
        {
            get { return deleteCommand; }
            set { deleteCommand = value; }
        }

        private ICommand refreshCommand;
        public ICommand RefreshCommand
        {
            get { return refreshCommand; }
            set { refreshCommand = value; }
        }

        // 显示第一页
        public ICommand BtnFirstCommand { get; set; }
        // 显示前一页
        public ICommand BtnPrevCommand { get; set; }
        // 显示后一页
        public ICommand BtnNextCommand { get; set; }
        // 显示最后一页
        public ICommand BtnLastCommand { get; set; }


        public RelayCommand<Employee> BtnCancelEditCommand { get; set; }
        public RelayCommand<Employee> BtnConfirmEditCommand { get; set; }

        private void BtnCancelEdit(Employee sender)
        {
            datagrid.CancelEdit();
        }


        private void BtnConfirmEdit(Employee sender)
        {

            datagrid.CommitEdit();
            employeeSerivce.Update(sender);
            Message = "修改成功!";
        }
        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
        {
            if (PropertyChanged != null)
            {
                PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public EmployeeService employeeSerivce;

        private Employee employee;
        public Employee Employee
        {
            get { return employee; }
            set { employee = value; NotifyPropertyChanged(); }
        }

        private ObservableCollection<Employee> employeeList;
        public ObservableCollection<Employee> EmployeeList
        {
            get
            {
                return employeeList;
            }
            set => SetProperty(ref employeeList, value);
        }

        // 是否是搜索模式，搜索模式下，所有数据源放在一个SearchList里面，前端界面仅仅显示SearchList的内容
        // 否则显示数据总条数、页数
        private bool isSearchMode = false;
        // 页码数
        private int page;
        public int Page { get { return page; }
            set => SetProperty(ref page, value);
        }

        // 每页大小
        private int pageSize = 10;
        public int PageSize {
            get { return pageSize; } 
            set { 
                if(value != pageSize)
                {
                    SetProperty(ref pageSize, value);
                    Page = 1;
                    InitEmployeeList();
                }
            }
        }

        // 每页大小的候选项
        private ObservableCollection<int> pageSizes = new ObservableCollection<int>(new int[]{ 10, 20, 30, 50, 100 });
        public ObservableCollection<int> PageSizes { get { return pageSizes; }}


        // 总页数
        private int totalCount;
        public int TotalCount
        { 
            get { return totalCount; }
            set => SetProperty(ref totalCount, value);
        }



        // 搜索结果集，这个集合不能直接显示到前端界面，为了分页方便，所以就存储在这里
        private ObservableCollection<Employee> searchList = new ObservableCollection<Employee>();
        public ObservableCollection<Employee> SearchList
        {
            get
            {
                return searchList;
            }
            set
            {
                searchList = value;
                NotifyPropertyChanged();
            }
        }

        public EmployeeViewMode()
        {
            Page = 1;
            employeeSerivce = new EmployeeService();
            //BindData();
            Employee = new Employee();
            AddCommand = new DelegateCommand(Add);
            SearchCommand = new DelegateCommand(GetEmployee);
            DeleteCommand = new DelegateCommand(Delete);
            RefreshCommand = new DelegateCommand(Refresh);
            
            BtnFirstCommand = new DelegateCommand(BtnFitst);
            BtnNextCommand = new DelegateCommand(BtnNext);
            BtnLastCommand = new DelegateCommand(BtnLast);
            BtnPrevCommand = new DelegateCommand(BtnPrev);

            BtnCancelEditCommand = new RelayCommand<Employee>(BtnCancelEdit);
            BtnConfirmEditCommand = new RelayCommand<Employee>(BtnConfirmEdit);
            InitEmployeeList();
        }

        // 初始化显示的参数
        public void InitEmployeeList()
        {
            if (!isSearchMode)
            {
                int totalNum = employeeSerivce.GetEmployeesCount();
                // 计算总页数
                TotalCount = (int)Math.Ceiling((double)totalNum / PageSize);
            }
            else
            {
                TotalCount = (int)Math.Ceiling((double)(SearchList.Count) / PageSize);
            }
            BtnFitst();
        }
        /// <summary>
        /// 跳转到搜索结果或者默认试图的第一页
        /// </summary>

        public void BtnFitst()
        {
            try
            {
                Page = 1;
                // 如果是搜索模式
                if (isSearchMode) {
                    EmployeeList = new ObservableCollection<Employee>(SearchList.Skip((Page - 1) * PageSize).Take(PageSize));
                }
                else
                {
                    employeeSerivce = new EmployeeService();
                    EmployeeList = employeeSerivce.BrowseEmployees(Page, PageSize);
                }
            }

            catch (Exception ex)
            {
                Message = ex.Message;
            }
        }


        /// <summary>
        /// 跳转到搜索结果或者默认试图的前一页
        /// </summary>
        public void BtnPrev()
        {
            if (Page == 1) return;
            Page -= 1;
            try
            {
                // 如果是搜索模式
                if (isSearchMode)
                {

                    EmployeeList = new ObservableCollection<Employee>(SearchList.Skip((Page - 1)*PageSize).Take(PageSize));
                }
                else
                {
                    employeeSerivce = new EmployeeService();
                    EmployeeList = employeeSerivce.BrowseEmployees(Page, PageSize);
                }
            }

            catch (Exception ex)
            {
                Message = ex.Message;
            }
        }

        /// <summary>
        /// 跳转到搜索结果或者默认试图的前一页
        /// </summary>
        public void BtnNext()
        {
            if (Page == TotalCount) return;
            Page += 1;
            try
            {
                // 如果是搜索模式
                if (isSearchMode)
                {

                    EmployeeList = new ObservableCollection<Employee>(SearchList.Skip((Page - 1) * PageSize).Take(PageSize));
                }
                else
                {
                    employeeSerivce = new EmployeeService();
                    EmployeeList = employeeSerivce.BrowseEmployees(Page, PageSize);
                }
            }

            catch (Exception ex)
            {
                Message = ex.Message;
            }
        }


        /// <summary>
        /// 跳转到搜索结果或者默认试图的最后一页
        /// </summary>
        public void BtnLast()
        {
            try
            {
                Page = TotalCount;
                // 如果是搜索模式
                if (isSearchMode)
                {
                    EmployeeList = new ObservableCollection<Employee>(SearchList.Skip((Page - 1) * PageSize).Take(PageSize));
                }
                else
                {
                    employeeSerivce = new EmployeeService();
                    EmployeeList = employeeSerivce.BrowseEmployees(Page, PageSize);
                }
            }

            catch (Exception ex)
            {
                Message = ex.Message;
            }
        }


        public void Refresh()
        {
            try
            {
                SearchList.Clear();
                isSearchMode = false;
                InitEmployeeList();
            }

            catch (Exception ex)
            {
                Message = ex.Message;
            }
        }

        /// <summary>
        /// 消息提示
        /// </summary>
        private string message;
        public string Message
        {
            get { return message; }
            set
            {
                SetProperty(ref message, value);
                System.Windows.MessageBox.Show(message);
            }
        }

        public void Add()
        {
            try
            {
                var emp = new Employee()
                {
                    PersonNo = Employee.PersonNo,
                    Name = Employee.Name,
                    Department = Employee.Department,
                    Tel = Employee.Tel,
                    Factory = Employee.Factory
                };
                bool isAdded = employeeSerivce.Add(emp);
                Message = isAdded ? "添加成功" : "添加失败";
            }

            catch (Exception ex)
            {
                Message = ex.Message;
            }
        }

        // 查询员工，提供姓名、电话号码、以及工号的模糊查询，将满足其中任意条件的全部
        public void GetEmployee()
        {
            try
            {
                isSearchMode = true;
                SearchList = employeeSerivce.GetEmployee(Employee);
                InitEmployeeList();
            }
            catch (Exception ex)
            {
                Message = ex.Message;
            }
        }

        public void UpdateEmployee(Employee emp)
        {
            try
            {

                Employee oldEmployee = employeeSerivce.GetEmployee(emp.ID);
                if (oldEmployee == emp)
                {
                    return;
                }
                bool isUpdated = employeeSerivce.Update(emp);
                if (isUpdated)
                {
                    Message = "修改成功";

                }
                else
                    Message = "修改失败";

            }
            catch (Exception ex)
            {
                Message = ex.Message;
            }
        }

        public void Delete()
        {
            try
            {
                bool isDeleted = employeeSerivce.Delete(SelectedEmployee.ID);

                if (isDeleted)
                {
                    Message = "删除成功";
                    EmployeeList.Remove(SelectedEmployee);
                }
                else
                {
                    Message = "删除失败";
                }
            }
            catch (Exception ex)
            {
                Message = ex.Message;
            }
        }
    }


}
